package com.hmall.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.hmall.common.utils.UserContext;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;


public class UserInfoInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中信息userId
        String userId = request.getHeader("user-info");
        System.err.println("<1>微服务调用前 common 拦截器中 userInfo= "+userId +" --- time: "+ LocalDateTime.now());
        //判断是否为空 ，不为空，存储到ThreadLocal
        if (StrUtil.isNotBlank(userId)){
            UserContext.setUser(Long.valueOf(userId));
        }
        //放行
//        return HandlerInterceptor.super.preHandle(request, response, handler);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除用户
        UserContext.removeUser();
    }
}
